<template>
  <view class="components-form">
    <!-- 顶部导航 -->
    <tn-nav-bar fixed>编辑套餐</tn-nav-bar>
    
    <!-- 页面内容 -->
    <view :style="{paddingTop: vuex_custom_bar_height + 'px'}" class="form-container">
      <tn-form 
        :model="formData" 
        ref="form" 
        :errorType="['message']" 
        labelPosition="left"
        :labelWidth="140"
        labelAlign="right"
      >
        <!-- 选择门店 -->
        <tn-form-item label="所属门店" prop="mchId" :required="true">
          <tn-input
            v-model="formData.mchId"
            type="select"
            placeholder="请选择门店"
            :selectOpen="storeSelectShow"
            @click="storeSelectShow = true"
          ></tn-input>
        </tn-form-item>
        
        <!-- 选择房间 -->
        <tn-form-item label="所属房间" prop="roomId" :required="true">
          <tn-input
            v-model="formData.roomId"
            type="select"
            placeholder="请选择房间"
            :selectOpen="roomSelectShow"
            @click="roomSelectShow = true"
            :disabled="!formData.mchId"
          ></tn-input>
        </tn-form-item>
        
        <!-- 套餐时长 -->
        <tn-form-item label="套餐时长" prop="hours" :required="true">
          <tn-number-box
            v-model="formData.hours"
            :min="1"
            :max="24"
            :step="0.5"
          >
            <text slot="suffix">小时</text>
          </tn-number-box>
        </tn-form-item>
        
        <!-- 套餐金额 -->
        <tn-form-item label="套餐金额" prop="amount" :required="true">
          <tn-input
            v-model="formData.amount"
            type="number"
            placeholder="请输入套餐金额"
          >
            <text slot="suffix">元</text>
          </tn-input>
        </tn-form-item>
        
        <!-- 套餐描述 -->
        <tn-form-item label="套餐描述" prop="descp">
          <tn-input
            v-model="formData.descp"
            type="textarea"
            placeholder="请输入套餐描述"
            :maxlength="200"
          />
        </tn-form-item>
        
        <!-- 备注 -->
        <tn-form-item label="备注" prop="remark">
          <tn-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :maxlength="200"
          />
        </tn-form-item>
      </tn-form>
      
      <!-- 底部按钮 -->
      <view class="bottom-btns">
        <tn-button backgroundColor="#01BEFF" fontColor="#FFFFFF" @click="submit">保存</tn-button>
        <tn-button backgroundColor="#FFFFFF" fontColor="#333333" @click="goBack" class="margin-left">返回</tn-button>
      </view>
      
      <!-- 门店选择器 -->
      <tn-select
        v-model="storeSelectShow"
        mode="single"
        :list="storeList"
        @confirm="storeSelectConfirm"
      ></tn-select>
      
      <!-- 房间选择器 -->
      <tn-select
        v-model="roomSelectShow"
        mode="single"
        :list="roomList"
        @confirm="roomSelectConfirm"
      ></tn-select>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      id: '', // 套餐ID
      storeSelectShow: false,
      roomSelectShow: false,
      storeList: [], // 门店列表
      roomList: [], // 房间列表
      formData: {
        mchId: '',
        roomId: '',
        hours: 1,
        amount: '',
        descp: '',
        remark: ''
      },
      rules: {
        mchId: [{
          required: true,
          message: '请选择所属门店',
          trigger: ['change']
        }],
        roomId: [{
          required: true,
          message: '请选择所属房间',
          trigger: ['change']
        }],
        hours: [{
          required: true,
          message: '请设置套餐时长',
          trigger: ['change']
        }],
        amount: [{
          required: true,
          message: '请输入套餐金额',
          trigger: ['blur', 'change']
        }, {
          pattern: /^([1-9]\d*|0)(\.\d{1,2})?$/,
          message: '请输入正确的金额格式',
          trigger: ['blur', 'change']
        }]
      }
    }
  },
  
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  
  onLoad(options) {
    this.getStoreList()
    if(options.id) {
      this.id = options.id
      this.getMealInfo()
    }
  },
  
  methods: {
    // 发送GET请求获取门店列表
    getStoreList() {
      uni.$u.http.get('/system/store/list').then(res => {
        if(res.data.code === 200) {
          this.storeList = res.data.data.map(item => ({
            label: item.mchName,
            value: item.id
          }))
        } else {
          uni.$u.toast(res.data.msg)
        }
      }).catch(err => {
        uni.$u.toast('获取门店列表失败')
      })
    },
    
    // 门店选择确认
    storeSelectConfirm(event) {
      const selectedStore = event[0]
      this.formData.mchId = selectedStore.value
      this.formData.roomId = ''
      this.getRoomList(selectedStore.value)
    },
    
  // 发送POST请求获取房间列表
  getRoomList(mchId) {
      uni.$u.http.post('/system/room/roomsByMchid', {
        mchid: mchId
      }).then(res => {
        if(res.data.code === 200) {
          this.roomList = res.data.data.map(item => ({
            label: item.roomName,
            value: item.id
          }))
        } else {
          uni.$u.toast(res.data.msg)
        }
      }).catch(err => {
        uni.$u.toast('获取房间列表失败')
      })
    },
    
    // 房间选择确认
    roomSelectConfirm(event) {
      this.formData.roomId = event[0].value
    },
    
    // 获取套餐信息
    getMealInfo() {
	  //发送GET请求获取特定套餐的详细信息
      uni.$u.http.get('/system/meal/info/' + this.id).then(res => {
        if(res.data.code === 200) {
          this.formData = res.data.data
          this.getRoomList(this.formData.mchId)
        } else {
          uni.$u.toast(res.data.msg)
        }
      }).catch(err => {
        uni.$u.toast('获取套餐信息失败')
      })
    },
    
    
    // 表单提交
    submit() {
      this.$refs.form.validate(valid => {
		//根据是否存在决定不同的URL，发送POST请求提交信息
        if(valid) {
          const url = this.id ? '/system/meal/edit' : '/system/meal/add'
          uni.$u.http.post(url, this.formData).then(res => {
            if(res.data.code === 200) {
              uni.$u.toast('保存成功')
              setTimeout(() => {
                this.goBack()
              }, 1500)
            } else {
              uni.$u.toast(res.data.msg)
            }
          }).catch(err => {
            uni.$u.toast('保存失败')
          })
        }
      })
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 30rpx;
  background-color: #f5f5f5;
}

.bottom-btns {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-around;
  
  .margin-left {
    margin-left: 20rpx;
  }
}
</style>